package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Order;
import cn.wolfcode.trip.base.mapper.OrderMapper;
import cn.wolfcode.trip.base.query.OrderQueryObject;
import cn.wolfcode.trip.base.service.IOrderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements IOrderService {

    //订单
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 根据id删除订单
     *
     * @param id
     * @return
     */
    @Override
    public int deleteByPrimaryKey(Long id) {
        return orderMapper.deleteByPrimaryKey(id);
    }

    /**
     * 新增购物车订单信息
     *
     * @param record
     * @return
     */
    @Override
    public int insert(Order record) {
        //新增的订单状态为1
        record.setType(1);
        //创建时间为当前
        record.setCreateTime(new Date());
        return orderMapper.insert(record);
    }

    /**
     * 新增支付订单信息
     *
     * @param order
     * @return
     */
    @Override
    public void insertPay(Order order) {
        Order order1 = orderMapper.selectOne(order.getId());
        if (order1 !=null && order1.getType()==1) {
            orderMapper.updateByPrimaryKey(order);
        }else {
            //新增的订单状态为2
            order.setType(2);
            //创建时间为当前
            order.setCreateTime(new Date());
            order.setOrderNum(1);
            try{

                orderMapper.insertPay(order);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @Override
    public Order selectByPrimaryKey(Long id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    @Override
    public Order selectOne(Long id) {
        return orderMapper.selectOne(id);
    }

    @Override
    public List<Order> selectAll() {
        return orderMapper.selectAll();
    }

    @Override
    public int updateByPrimaryKey(Order record) {
        return orderMapper.updateByPrimaryKey(record);
    }

    //查询所有商品
    @Override
    public PageInfo query(OrderQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<Order> list = orderMapper.selectForList(qo);
        return new PageInfo(list);
    }

    //查询购物车商品
    @Override
    public PageInfo list(OrderQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());
        List<Order> list = orderMapper.selectForListByTypeAndUserId(qo);
        return new PageInfo(list);
    }

}
